package com.tengju.bff.interfaces.shared.servlet;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 风险等级拦截
 * @author kezunfa
 */
@Component
@Slf4j
@Aspect
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class RiskLevelAction {

    @Value("#{${controller.common.risk.level.status.map}}")
    private Map<String,Integer> riskLevelStatusMap;

    private final ApplicationContext applicationContext;

    @Pointcut("@annotation(com.tengju.bff.interfaces.shared.servlet.RiskLevel)")
    public void controllerAspect() {
    }

    @Around(value = "controllerAspect() && @annotation(riskLevel)")
    public Object around(ProceedingJoinPoint joinPoint, RiskLevel riskLevel) throws Throwable {
        // 获取策略
        RiskLevelEnum riskLevelEnum =
                RiskLevelEnum.getByLevel(riskLevelStatusMap.get(riskLevel.key()));
        if (riskLevelEnum != null) {
            try {
                RiskLevelStrategy strategy =
                        (RiskLevelStrategy) applicationContext.getBean(riskLevelEnum.getStrategy());
                return strategy.action(joinPoint);
            } catch (BeansException e) {
                log.warn("找不到策略bean:{}",riskLevelEnum.getStrategy());
                return joinPoint.proceed();
            }
        }

        // 返回结果
        return joinPoint.proceed();
    }
}
